# frozen_string_literal: true

module Wpxf
  module Net
    # Provides helper functions for interfacing with Typhoeus in a module.
    module TyphoeusHelper
      def advanced_typhoeus_options
        {
          userpwd: datastore['basic_auth_creds'],
          proxy: datastore['proxy'],
          proxyuserpwd: datastore['proxy_auth_creds'],
          ssl_verifyhost: normalized_option_value('verify_host') ? 2 : 0,
          ssl_verifypeer: normalized_option_value('verify_peer'),
          timeout: normalized_option_value('http_client_timeout')
        }
      end

      def standard_typhoeus_options(method, params, body, headers)
        {
          method: method,
          body: body,
          params: params,
          headers: base_http_headers.merge(headers),
          followlocation: normalized_option_value('follow_http_redirection')
        }
      end

      def create_typhoeus_request_options(method, params, body, headers)
        standard_typhoeus_options(method, params, body, headers)
          .merge(advanced_typhoeus_options)
      end

      def create_typhoeus_request(opts)
        headers = opts[:headers] || {}
        headers['Cookie'] = opts[:cookie] if opts[:cookie]
        options = create_typhoeus_request_options(
          opts[:method],
          opts[:params],
          opts[:body],
          headers
        )
        Typhoeus::Request.new(normalize_relative_uri(opts[:url]), options)
      end
    end
  end
end
